<template>
  <div class="plan-area-view">

    <div style="display: flex;align-items: center;margin-bottom: 20px">
      <el-button
        class="main-btn"
        size="small"
        type="primary"
        @click="onAdd"
      >添加地区</el-button>
      <el-button
        class="main-btn"
        size="small"
        type="primary"
        @click="allDelete"
      >全部删除</el-button>
    </div>

    <el-table
      :data="tableData"
      border
      header-cell-class-name="table-header"
    >
      <el-table-column
        label="序号"
        type="index"
        width="55"
      />
      <el-table-column
        align="center"
        header-align="center"
        label="规划招商地区"
        width="150"
      >
        <template #default="scope">

          <el-cascader
            v-if="scope.row.isEdit"
            v-model="scope.row.area"
            :options="citys"
            :props="{ checkStrictly : true, expandTrigger: 'hover', label: 'regionName', value:'regionCode' }"
            :show-all-levels="false"
            placeholder="请选择规划招商地区"
            style="width: 100%;"
            @change="(val) => {areaChange(val,scope.row,scope.$index)}"
          />
          <span v-else>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        header-align="center"
        label="招商类型"
        width="150"
      >
        <template #default="scope">
          <span>{{ getLabel('plan_type', scope.row.detailPlanType) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        header-align="center"
        label="代理周期"
        width="150"
      >
        <template #default="scope">

          <div
            v-if="scope.row.isEdit"
            style="display: flex"
          >
            <el-input v-model.number="scope.row.agentCycle" />
            <span style="margin-left: 10px">年</span>
          </div>
          <span v-else>{{ scope.row.agentCycle }}年</span>

        </template>
      </el-table-column>
      <el-table-column
        align="center"
        header-align="center"
        label="最低销量"
        min-width="150"
      >
        <template #default="scope">

          <div style="display: flex;justify-content: center">
            <template v-if="scope.row.minSale">
              <span v-if="scope.row.isIncrease == 1">{{ scope.row.minSale }}{{
                getLabel('sell_unit', datas.sellUnit)
              }}/年</span>
              <span v-else>首年{{ scope.row.minSale }}{{
                getLabel('sell_unit', datas.sellUnit)
              }},每年递增{{ scope.row.increaseNum }}%</span>
            </template>
            <el-button
              v-if="scope.row.isEdit"
              style="margin-left: 10px"
              type="text"
              @click.stop="editNum(scope.row)"
            >设置
            </el-button>
          </div>

        </template>
      </el-table-column>
      <el-table-column
        align="center"
        header-align="center"
        label="销量保证金(元)"
      >
        <template #default="scope">
          <template v-if="scope.row.isEdit">
            <el-input
              v-model.number="scope.row.sellEarnestMoney"
              placeholder="请输入销量保证金"
            />
          </template>

          <span v-else>
            {{ scope.row.sellEarnestMoney }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        header-align="center"
        label="其他说明"
      >
        <template #default="scope">
          <el-input
            v-if="scope.row.isEdit"
            v-model="scope.row.remark"
            placeholder="请输入其他说明"
          />

          <div v-else>
            {{ scope.row.remark }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        header-align="center"
        label="操作"
      >
        <template #default="scope">
          <el-button
            v-if="!scope.row.isEdit"
            type="text"
            @click="onEdit(scope.row)"
          >编辑</el-button>
          <el-button
            v-else
            type="text"
            @click="onConfirm(scope.row)"
          >完成</el-button>
          <el-button
            type="text"
            @click="onDelete(scope)"
          >移除</el-button>
        </template>
      </el-table-column>

    </el-table>

    <sellNumDialog
      ref="sellNumDialog"
      :datas="datas"
    />

  </div>
</template>

<script>
import sellNumDialog from './sellNumDialog.vue'
import {
  computed,
  defineComponent,
  getCurrentInstance,
  onMounted,
  reactive,
  toRefs,
} from 'vue'

export default defineComponent({
  name: 'AreaView',
  components: { sellNumDialog },
  props: {
    list: {
      type: Array,
      default: [],
    },
    area: {
      type: Array,
      default: [],
    },
    datas: {
      type: Object,
      default: {},
    },
    deletes: {
      type: Array,
      default: [],
    },
  },
  setup(props, { emit }) {
    const currentInstance = getCurrentInstance()
    var data = reactive({
      selects: [],
      row: {},
      sellNumDialog: null,
    })

    onMounted(() => {})

    var tableData = computed({
      get() {
        return props.list
      },
      set(val) {
        emit('update:list', val)
        return val
      },
    })

    var citys = computed({
      get() {
        const arr = checkDisableArea(props.area)
        return arr
      },
    })

    const editNum = (row) => {
      data.row = row
      data.sellNumDialog.open(row)
    }

    const onDelete = (scope) => {
      if (scope.row.id) {
        props.deletes.push(scope.row.id)
      }

      tableData.value.splice(scope.$index, 1)
      checkSelects()
    }

    const onConfirm = (row) => {
      // if (!row.name) {
      //   currentInstance.proxy.customMessage({ type: 'error', message: '请选择规划招商地区' })
      //   return
      // }
      // if (!row.agentCycle) {
      //   currentInstance.proxy.customMessage({ type: 'error', message: '请输入代理周期' })
      //   return
      // }
      // if (!row.minSale) {
      //   currentInstance.proxy.customMessage({ type: 'error', message: '请输入最低销量' })
      //   return
      // }
      // if (!row.sellEarnestMoney) {
      //   currentInstance.proxy.customMessage({ type: 'error', message: '请输入销量保证金' })
      //   return
      // }
      row.agentCycle = Number(row.agentCycle)
      row.minSale = Number(row.minSale)
      row.sellEarnestMoney = Number(row.sellEarnestMoney)
      row.isEdit = false
    }

    const onEdit = (row) => {
      row.isEdit = true
    }

    const onAdd = () => {
      const a = {
        isEdit: true,
        name: '',
        areaCode: '',
        provinceCode: '',
        cityCode: '',
        agentCycle: '',
        isIncrease: '1',
        sellEarnestMoney: '',
        minSale: '',
        minSaleUnit: '1',
        increaseNum: '',
        detailPlanType: '',
      }
      tableData.value.push(a)
    }

    const allDelete = () => {
      const arr = []
      for (let i = 0; i < tableData.value.length; i++) {
        if (tableData.value[i].id) {
          arr.push(tableData.value[i].id)
        }
      }
      props.deletes = props.deletes.concat(arr)
      tableData.value = []
      checkSelects()
    }

    const getArea = () => {
      const arr = checkDisableArea(props.area)
      return arr
    }

    const checkDisableArea = (list) => {
      const arr = []
      for (let i = 0; i < list.length; i++) {
        const a = { ...list[i] }
        a.disabled =
          data.selects.findIndex((area) => area == a.regionCode) != -1
        // if (a.disabled) {
        //   a.children = null
        // }
        if (a.children) {
          a.children = checkDisableArea(a.children)
        }

        arr.push(a)
      }
      return arr
    }

    const checkSelects = () => {
      data.selects = []
      for (let i = 0; i < tableData.value.length; i++) {
        const a = tableData.value[i]
        if (a.areaCode) {
          data.selects.push(a.areaCode)
        } else if (a.cityCode) {
          data.selects.push(a.cityCode)
        } else if (a.provinceCode) {
          data.selects.push(a.provinceCode)
        }
      }
    }

    const areaChange = (val, row, index) => {
      let name = ''
      const province =
        props.area[props.area.findIndex((a) => a.regionCode == val[0])]
      let city = {}
      let area = {}
      if (!checkSelectArea(val, index)) {
        const areaList = []
        if (row.provinceCode) {
          areaList.push(row.provinceCode)
        }
        if (row.cityCode) {
          areaList.push(row.cityCode)
        }
        if (row.areaCode) {
          areaList.push(row.areaCode)
        }
        row.area = areaList
        return
      }
      if (val.length == 1) {
        // if (data.selects.findIndex(area => area.slice(0, 2) == val[0].slice(0, 2)) != -1) {
        //   currentInstance.proxy.customMessage({ type: 'error', message: '已存在下级区域，当前无法选择' })
        //   row.area = []
        //   return
        // }
        name = province.regionName
        row.detailPlanType = 'province'
      } else if (val.length == 2) {
        // if (data.selects.findIndex(area => area.slice(0, 4) == val[1].slice(0, 4)) != -1) {
        //   currentInstance.proxy.customMessage({ type: 'error', message: '已存在下级区域，当前无法选择' })
        //   row.area = []
        //   return
        // }
        city =
          province.children[
            province.children.findIndex((a) => a.regionCode == val[1])
          ]
        name = city.regionName
        row.detailPlanType = 'city'
      } else if (val.length == 3) {
        city =
          province.children[
            province.children.findIndex((a) => a.regionCode == val[1])
          ]
        area =
          city.children[city.children.findIndex((a) => a.regionCode == val[2])]
        name = city.regionName + '/' + area.regionName
        row.detailPlanType = 'area'
      }

      row.provinceCode = province.regionCode
      row.cityCode = city.regionCode ? city.regionCode : ''
      row.areaCode = area.regionCode ? area.regionCode : ''
      row.name = name

      checkSelects()
    }

    const checkSelectArea = (val, index) => {
      let bo = true

      if (val.length == 1) {
        const list = []
        for (let i = 0; i < data.selects.length; i++) {
          if (data.selects[i].slice(0, 2) == val[0].slice(0, 2)) {
            list.push(i)
          }
        }
        if (list.length > 1 || (list.length == 1 && list[0] != index)) {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: '已存在下级区域，当前无法选择',
          })
          bo = false
        }
      } else if (val.length == 2) {
        let provinceIndex = -1
        const areas = []
        for (let i = 0; i < data.selects.length; i++) {
          if (data.selects[i] == val[0].slice(0, 2) + '0000') {
            provinceIndex = i
          } else if (data.selects[i].slice(0, 4) == val[1].slice(0, 4)) {
            areas.push(i)
          }
        }
        if (provinceIndex != -1 && provinceIndex != index) {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: '已存在上级区域，当前无法选择',
          })
          bo = false
        } else if (
          areas.length > 1 ||
          (areas.length == 1 && areas[0] != index)
        ) {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: '已存在下级区域，当前无法选择',
          })
          bo = false
        }
      } else {
        const x = data.selects.findIndex(
          (area) =>
            area == val[2].slice(0, 4) + '00' ||
            area == val[2].slice(0, 2) + '0000'
        )
        if (x != -1 && x != index) {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: '已存在上级区域，当前无法选择',
          })
          bo = false
        }
      }
      return bo
    }

    return {
      ...toRefs(data),
      tableData,
      citys,

      onDelete,
      onAdd,
      allDelete,
      onEdit,
      areaChange,
      getArea,
      onConfirm,
      editNum,
    }
  },
})
</script>

<style scoped>
</style>
